package club.beimeng.eduservice.service.impl;

import club.beimeng.eduservice.entity.EduSubject;
import club.beimeng.eduservice.entity.excel.SubjectData;
import club.beimeng.eduservice.entity.subject.OneSubject;
import club.beimeng.eduservice.entity.subject.TwoSubject;
import club.beimeng.eduservice.listener.SubjectExcelListener;
import club.beimeng.eduservice.mapper.EduSubjectMapper;
import club.beimeng.eduservice.service.EduSubjectService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-07-24
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            //调用方法进行调用
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        // answerList 最终结果集合
        ArrayList<OneSubject> answerList = new ArrayList<>();

        // 1 查询出所有的一级分类 parentId = 0
        QueryWrapper<EduSubject> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id","0");

        List<EduSubject> oneEduSubjects = baseMapper.selectList(wrapper1);
        // 2 查询出所有的二级分类
        QueryWrapper<EduSubject> wrapper2 = new QueryWrapper<>();
        wrapper2.ne("parent_id","0");

        List<EduSubject> twoEduSubjects = baseMapper.selectList(wrapper2);
        // 3 封装一级分类
        //查询出来的所有一级分类list集合编列，
        oneEduSubjects.forEach((eduSubject) -> {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject); /* 这个函数将会把前者中的数据拿出来再set到后者的属性中 */

            ArrayList<TwoSubject> children = new ArrayList<>(); /*获得所有的子级分类*/
            twoEduSubjects.forEach((eduSubject2 -> {
                if (eduSubject2.getParentId().equals(eduSubject.getId())){ /*如果是子级*/
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(eduSubject2,twoSubject);
                    children.add(twoSubject);
                }
            }));
            oneSubject.setChildren(children);
            answerList.add(oneSubject);
        });

        //4 封装二级分类
        return answerList;
    }
}
